<template>
  <div>
    <a-page-header
      style="border: 1px solid rgb(235, 237, 240)"
      title="服务提报详情"
      :ghost="false"
      @back="() => $router.go(-1)"
    ></a-page-header>

    <page-header-wrapper>
      <a-card :bordered="false">
        <template v-if="clearData">
          <a-alert message="提示" type="info" style="margin-bottom: 20px">
            <div slot="description">
              <div>支付宝小程序URL：{{ clearData.alipay_url }}</div>
              <div>门店ID：{{ clearData.shop_id }}</div>
            </div>
          </a-alert>
        </template>

        <a-form-model
          ref="alipayForm"
          :model="alipayForm"
          :rules="alipayRules"
          :label-col="{ span: 3 }"
          :wrapper-col="{ span: 11 }"
        >
          <a-form-model-item label="小程序" prop="id">
            <a-select placeholder="请选择小程序" :disabled="disabled" v-model="alipayForm.id" @change="changeId">
              <a-select-option :value="item.id" v-for="item of idList" :key="item.id">
                {{ item.app_name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>

          <a-form-model-item label="行业类型" prop="category_id" v-if="alipayForm.id">
            <a-select
              :disabled="disabled"
              v-model="alipayForm.category_id"
              showSearch
              @change="changeCat"
              :filterOption="filterOption"
            >
              <a-select-option :value="item.value" v-for="(item, index) of categoryList" :key="index">
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>

          <!-- 支付宝动态表单 start -->
          <template v-if="xxml">
            <template v-for="(item, index) of xxml.attribute">
              <customForm :areaList="areaList" :item="item" :key="index" :disabled="disabled"></customForm>
            </template>
          </template>
          <!-- 支付宝动态表单 end -->

          <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
            <a-button v-loading="btnLoading" :disabled="disabled" type="primary" @click="onSubmit"> 提交 </a-button>
            <a-button style="margin-left: 10px" @click="$router.go(-1)"> 取消 </a-button>
          </a-form-model-item>
        </a-form-model>
      </a-card>
    </page-header-wrapper>
  </div>
</template>

<script>
import {
  serviceApply,
  serviceQuery,
  serviceListQuery,
  getServiceCats,
  getServiceSchema,
  areaList,
} from '@/api/marketing/alipayPromotion'
import { alipayList, basedata } from '@/api/setting/applet'
import { cyyUploadImg } from '@/components/CyyUi/index'
export default {
  components: {
    cyyUploadImg,
    customForm: () => import('./components/form'),
  },

  data() {
    let checkPic = (rule, value, callback) => {
      if (this.alipayForm.license_pic == '') {
        callback(new Error('请上传公司营业执照'))
      } else {
        callback()
      }
    }

    return {
      btnLoading: false,
      disabled: false,
      data: null,
      areaList: [],
      idList: [],
      categoryList: [],
      alipayForm: {
        id: '',
        service_code: '',
        category_id: '',
      },
      xxml: null,

      // 支付宝验证规则
      alipayRules: {
        id: [{ required: true, message: '请先选择小程序', trigger: 'change' }],
        category_id: [{ required: true, message: '请选择类型', trigger: 'change' }],
      },

      clearData: null,
    }
  },

  computed: {},

  methods: {
    async changeId(id) {
      let res = await basedata({
        id,
      })

      if (!res.code) {
        console.log('res,', res)
        this.clearData = res.data
      } else {
        this.clearData = null
      }
    },

    // 将输入的内容与显示的内容进行匹配
    filterOption(value, option) {
      return option.componentOptions.children[0].text.indexOf(value) >= 0
    },

    clearVal(item) {
      if (item.value && JSON.stringify(item.value) === '{}') {
        item.value = ''
      } else {
        if (item.attributes && Array.isArray(item.attributes.attribute)) {
          item.attributes.attribute.forEach((el) => {
            this.clearVal(el)
          })
        }
      }
    },

    setSingleObjct(item) {
      // 如果是嵌套表单 && 只有一个选项则 修改为数组
      if (
        ((item['@attributes'].type === 'complex' && item['@attributes'].valueType === 'object') ||
          (item['@attributes'].type === 'multiComplex' && item['@attributes'].valueType === 'object')) &&
        item.attributes.attribute.length === 1
      ) {
        item.attributes.attribute = item.attributes.attribute[0]
      }
    },

    getNewData(obj, clear = false) {
      if (!obj) return obj

      obj.attribute.forEach((item) => {
        // 如果是嵌套表单 && 只有一个选项则 修改为数组
        if (
          ((item['@attributes'].type === 'complex' && item['@attributes'].valueType === 'object') ||
            (item['@attributes'].type === 'multiComplex' && item['@attributes'].valueType === 'object')) &&
          !Array.isArray(item.attributes.attribute)
        ) {
          item.attributes.attribute = [item.attributes.attribute]
        }
      })

      // 遍历初始化数据
      if (clear) {
        obj.attribute.forEach((item) => {
          this.clearVal(item)
        })
      }

      return obj
    },

    changeCat() {
      let { category_id: cid, id } = this.alipayForm

      const hide = this.$message.loading('请稍等', 0)
      getServiceSchema({
        id,
        cid,
      })
        .then((res) => {
          hide()

          if (!res.code) {
            let xxml = res.xxml
            this.xxml = this.getNewData(xxml, true)
          }
        })
        .catch(() => {
          hide()
        })
    },

    // 点击提交
    onSubmit() {
      this.$refs.alipayForm.validate(async (valid) => {
        if (valid) {
          this.btnLoading = true
          let xxml = JSON.parse(JSON.stringify(this.xxml))

          xxml.attribute.forEach((item) => {
            this.setSingleObjct(item)
          })

          const res = await serviceApply({
            ...this.alipayForm,
            xxml,
          })

          this.btnLoading = false

          if (!res.code) {
            this.$message.success(res.msg)
            this.$router.back()
            return
          }

          this.$message.error(res.msg)
        } else {
          return false
        }
      })
    },

    // // 选中职业执照照片
    // choosePic(e, type) {
    //   if (type == 'alipay') {
    //     this.alipayForm.license_pic = e.data
    //   }
    //   this.analysis(e.data, type)
    // }

    // // 解析营业执照
    // async analysis(url, type) {
    //   const res = await ocr({ url, type: 1 })
    //   if (res.code == 0) {
    //     this.alipayForm.legal_personal_name = res.data.person
    //     this.alipayForm.license_name = res.data.name
    //     this.alipayForm.license_no = res.data.reg_num
    //   }
    //   if (res.code == -1) {
    //     return
    //   }
    // },
  },

  async mounted() {
    const hide = this.$message.loading('请稍等', 0)
    let res = await alipayList(),
      res2 = await getServiceCats(),
      res3 = await areaList()

    if (!res.code && res.data.length) {
      this.idList = res.data
    }

    if (!res2.code && res2.data.length) {
      this.categoryList = res2.data.map((el) => {
        return {
          value: el[0],
          name: el.splice(1, 3).join('/'),
        }
      })
    }

    if (!res3.code && res3.data && res3.data.area_code) {
      this.areaList = res3.data.area_code
    }

    if (this.$route.query.service_code) {
      let { service_code } = this.$route.query
      this.alipayForm.service_code = service_code
      this.disabled = true

      let detail = await serviceQuery(service_code)
      if (!detail.code) {
        console.log('detail,', detail)
      } else {
        this.$message.error(detail.msg)
      }
    }

    hide()
    // // 测试
    // getServiceSchema({
    //   id: '8',
    //   cid: 'C000003266'
    // })
    //   .then(res => {
    //     hide()

    //     if (!res.code) {
    //       let xxml = res.xxml
    //       this.xxml = this.getNewData(xxml, true)
    //     }
    //   })
    //   .catch(() => {
    //     hide()
    //   })
  },
}
</script>

<style lang="less" scoped>
.title {
  font-size: 16px;
  color: rgba(0, 0, 0, 0.85);
  margin-bottom: 14px;
}
</style>
